package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"math"
	"os/exec"
	"strings"
)

type APIController struct {
	beego.Controller
}

func (a *APIController) Duration() {
	// 1. 获取参数
	url := a.GetString("url", "")
	if url == "" {
		a.Ctx.WriteString(fmt.Sprintf("%v", "error"))
		return
	}

	// FFmpeg 命令
	//  exec('ffmpeg -i ' . $url . ' 2>&1 | grep "Duration" | cut -d " " -f 4 | sed s/,//', $outDuration, $statusDuration);
	// cmd := exec.Command("ffmpeg", "-i", "input.mp4", "-vcodec", "libx264", "-acodec", "aac", "-strict", "-2", "output.mp4")

	// 执行FFmpeg命令获取音频时长
	cmd := exec.Command("ffprobe", "-i", url, "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0")
	output, err := cmd.CombinedOutput()
	if err != nil {
		logs.Info("ffmpeg err:", err)
		a.Ctx.WriteString(fmt.Sprintf("{\"code\":500,\"data\":{},\"message\":\"error\"}"))
		return
	}

	// 解析FFmpeg输出结果，获取音频时长
	durationStr := strings.TrimSpace(string(output))
	var duration float64
	_, err = fmt.Sscanf(durationStr, "%f", &duration)
	if err != nil {
		a.Ctx.WriteString(fmt.Sprintf("{\"code\":500,\"data\":{},\"message\":\"error\"}"))
		return
	}

	// 输出JSON音频时长
	a.Ctx.WriteString(fmt.Sprintf("{\"code\":0,\"data\":{\"duration\":%d},\"message\":\"success\"}", int(math.Ceil(duration))))
	return
}
